package com.zh.controller;


import com.zh.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @Autowired
    UserService userService;

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("msg","hello-shiro");
        return "index";
    }
    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLong(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录信息
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            //登录方法，没有抛出异常说明登录成功
            subject.login(token);
            return "index";
        }catch (UnknownAccountException ua){ //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException ic) { // 密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
        //


    }
    @RequestMapping("/user")
    public String getUser(String username){
        System.out.println(userService.getUserByUsername(username));
        return "hello-user";
    }

}
